import time
import pywifi
from pywifi import const

wifi = pywifi.PyWiFi()
iface = wifi.interfaces()[0]
profile = pywifi.Profile()

# 状态信息
status = {
    const.IFACE_CONNECTED: "CONNECTED",
    const.IFACE_CONNECTING: "CONNECTING",
    const.IFACE_DISCONNECTED: "DISCONNECTED",
    const.IFACE_INACTIVE: "INACTIVE",
    const.IFACE_SCANNING: "SCANNING"
}


# 配置配置信息
def _init_profile(wifi_profile):
    profile.ssid = wifi_profile["SSID"]
    profile.auth = wifi_profile["AUTH"]
    profile.akm.append(wifi_profile["AKM"])
    profile.cipher = wifi_profile["CIPHER"]
    profile.key = wifi_profile["KEY"]


# 断开网络连接
def net_disconnect():
    iface.disconnect()
    time.sleep(1)
    assert iface.status() in [const.IFACE_DISCONNECTED, const.IFACE_INACTIVE]


# 连接wifi
def net_connect(wifi_profile):
    # 先断开连接
    net_disconnect()
    # 配置信息
    _init_profile(wifi_profile)
    # 删除所有的配置信息
    # iface.remove_all_network_profiles()
    # 添加这个wifi的配置信息
    tmp_profile = iface.add_network_profile(profile)
    # 连接wifi
    iface.connect(tmp_profile)
    # 等待连接成功
    while iface.status() != const.IFACE_CONNECTED:
        pass
    assert iface.status() == const.IFACE_CONNECTED


# 获取网络连接状态
def net_status():
    return status[iface.status()]
